import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import moment from 'moment';
import { DATA_ENTRY, AdvancedSearch, TableC, FirstHeaderC, ExportC, NoQueryC, ContentPackage } from '../../../comps';
import { findValueByCode } from '../../../utils/utils';
import config from '../../../comps/business/tradingMarket/config';
import { getUserInfo } from '../../../utils/commonFunc';
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 6, offset: 0 },
    xxl: { span: 5, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 17, offset: 0 },
    xxl: { span: 17, offset: 0 },
  },
};
@connect(({ positionThroughQueryM, globalM, loading }) => ({
  positionThroughQueryM,
  globalM,
  loading,
}))
@Form.create()
export default class PositionThroughQuery extends PureComponent {
  state = {
    columns: undefined,
    dataSource: undefined, //
    currentPage: 1, //页码
    numInPage: 20, //每页条数
    currentPageAdujst: 1, //页码 拆分
    pageInfo: {}, //后端返回的页码信息
    searchObj: {}, //查询条件
    isReset: false, //是否点击重置
    columnsDefault: [
      { title: '产品名称', key: 'productName', width: 200 },
      { title: '资产类别', key: 'assetClass', width: 90 },
      { title: '证券代码', key: 'tradingCode', width: 150 },
      { title: '证券名称', key: 'secuabbr', width: 150 },
      { title: '交易场所', key: 'exchangeCode', width: 100 },
      { title: '持仓数量', key: 'holdAmount', type: 'number', toFixed: 2, width: 120 },
      { title: '市值', key: 'marketValue', type: 'money', width: 120 },
      { title: '成本价', key: 'costPrice', type: 'money', toFixed: 2, width: 120 },
      { title: '回购方向', key: 'direction', width: 100 },
      { title: '回购利率(%)', key: 'repoRate', type: 'rate', width: 100 },
      { title: '交易对手', key: 'counterparty', width: 120 },
      { title: '到期日', key: 'endDate', type: 'date', formatStr: 'YYYY-MM-DD HH:mm:ss', width: 120 },
    ],
    tradeDate: undefined, //最近一次交易日
  };
  componentDidMount() {
    // this.queryTableList();
    this.queryTradeDate(); //查询前一个交易日
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  //查询前一个交易日
  queryTradeDate = () => {
    this.props.dispatch({
      type: 'positionThroughQueryM/queryTradeDate',
      payload: {
        date: moment(new Date()).format('YYYY-MM-DD'),
        tenant: getUserInfo()?.tenantName,
      },
      callback: (data) => {
        if (data) {
          this.AdvancedSearch.props.form.setFieldsValue({
            date: moment(data),
          });
          this.setState({
            tradeDate: moment(data),
          });
        }
      },
    });
  };

  //查询列表
  queryTableList = () => {
    const {
      globalM: {
        dataDictionary: { FUTURE_CASHFLOW_TYPE = [] },
      },
    } = this.props;
    const { searchObj, isReset, numInPage, currentPage, columnsDefault, columnsChild } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    this.setState({
      columns: undefined,
      dataSource: undefined,
      pageInfo: {},
    }); //查询之前清除数据
    const params = {
      ...searchObj,
      date: searchObj.date ? searchObj.date.format('YYYY-MM-DD') : undefined,
      currentPage,
      numInPage,
    };
    this.props.dispatch({
      type: 'positionThroughQueryM/queryTableList',
      payload: {
        ...params,
      },
      callback: (data) => {
        if (data) {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columns: [...columnsDefault],
            dataSource: data.dataSource ? [...data.dataSource] : [],
            pageInfo: data.pageInfo || {},
          });
        } else {
          this.setState({
            columns: [...columnsDefault],
            dataSource: [],
            pageInfo: {},
          });
        }
      },
    });
  };

  //表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryTableList();
      },
    );
  };

  //表格列表
  renderTable = () => {
    const { currentPage, numInPage, columns, dataSource, pageInfo } = this.state;
    const {
      globalM: {
        dataDictionary: { LIMITATION_ASSET_TYPE = [], REPURCHASE_DIRECTION = [] },
      },
    } = this.props;
    columns &&
      columns.map((item) => {
        if (item.key == 'exchangeCode') {
          item.render = (text, record) => {
            if (text) {
              let findvalue = config.filter((item) => {
                return item.value == text;
              });
              if (findvalue && findvalue.length > 0) {
                return findvalue[0].title;
              } else {
                return '--';
              }
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'assetClass') {
          item.render = (text, record) => {
            if (text == undefined || text == null) return '--';
            return findValueByCode(text, LIMITATION_ASSET_TYPE);
          };
        }
        if (item.key == 'direction' || item.key == 'counterparty' || item.key == 'endDate' || item.key == 'repoRate') {
          item.render = (text, record) => {
            if (record.assetClass != 'HG' && !record.endDate) {
              return undefined; //只有回购展示这三项 或者  后端如果返回了到期日的 也要展示
            } else {
              if (item.key == 'direction') {
                if (text == undefined || text == null) return '--';
                else return findValueByCode(text, REPURCHASE_DIRECTION);
              }
              if (item.key == 'repoRate') {
                if (text == undefined || text == null) return '--';
                else return (text * 1).toFixed(2);
              } else {
                if (text == undefined || text == null) return '--';
                else return text;
              }
            }
          };
        }
      });
    return (
      <div>
        <TableC
          rowKey='key'
          selfScrollY={true}
          onChange={this.handleTableChange}
          current={currentPage}
          total={pageInfo.total || 0}
          pageSize={numInPage}
          columns={columns}
          dataSource={dataSource}
          scroll={{ x: 'max-content' }}
        />
      </div>
    );
  };

  render() {
    const { searchObj } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'productId',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          multiple: false,
        },
        {
          dataIndex: 'date',
          title: '截止日期',
          type: DATA_ENTRY.SINGLEDATE,
          formItemLayout: FormItemLayout,
          disableEnd: this.state.tradeDate ? moment(this.state.tradeDate).add(1, 'days') : undefined,
          allowClear: false,
        },
        {
          dataIndex: 'isPassThrough',
          title: '是否穿透',
          type: DATA_ENTRY.SELECT,
          isTrueFalseJudge: true,
          initialValue: '1',
        },
      ],
      onQuery: (e) => {
        if (!this.flag) this.flag = true; //判断当前是否点击过查询按钮
        if (e) {
          if (!e.date) {
            message.warning('截止日期不能为空');
            return;
          }
        }
        this.setState(
          {
            searchObj: e || {},
            currentPage: 1,
            isReset: false,
          },
          () => {
            this.queryTableList(); //点击查询按钮
          },
        );
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: { date: this.state.tradeDate }, //查询条件
          isReset: true,
        });
        this.AdvancedSearch.props.form.setFieldsValue({ date: this.state.tradeDate });
      },
      onRef: (ref) => {
        this.AdvancedSearch = ref;
      },
    };

    return (
      <ContentPackage
        title='穿透持仓查询'
        contentHtml={
          <div>
            <div>
              <AdvancedSearch {...searchProps} />
            </div>
            <div style={{ marginBottom: '16px', marginTop: '20px' }}>
              <ExportC
                url={'gateway/limitation-report/limitation/export'}
                search={{ ...searchObj, date: moment(searchObj.date ? searchObj.date.format('YYYY-MM-DD') : undefined).format('YYYY-MM-DD') }}
                disabled={this.state.dataSource && this.state.dataSource?.length ? false : true}
              />
            </div>
            {this.flag ? (
              this.renderTable()
            ) : (
              <div style={{ marginTop: '10px' }}>
                <NoQueryC />
              </div>
            )}
          </div>
        }
      />
    );
  }
}
